from osv import osv, fields
import tools.sql

class kderp_quotation_revision(osv.osv):
    #Update wkf sale.order.basic on_create false
    #Sale Process False
    _description = 'KDERP Quotation Revision'
    _name='kderp.quotation.revision'
    _auto=False
    
    _columns = {
                'order_id':fields.many2one('sale.order','Link to main'),
                'quotation_related_id':fields.many2one('sale.order','Related Quotation'),
                'submitdate':fields.date('Submit Date'),
                'state': fields.selection([
                    ('draft', 'Planning'),
                    ('work_received','Waiting for Contract'),
                    ('done', 'Contracted'),
                    ('cancel', 'Cancelled')
                    ], 'Quo. Status',readonly=True, select=1),
                }
    def init(self,cr):
        cr.execute("""create or replace view kderp_quotation_revision
                                as
                                    Select 
                                        (so.id::text || sor.id::text)::int as id,
                                        so.id as order_id,
                                        sor.id as quotation_related_id,
                                        sor.dateofsubmit as submitdate,
                                        sor.state
                                    from 
                                        sale_order so
                                    inner join
                                        sale_order sor on so.name ilike substring(sor.name from 1 for length('2012-SBY-0001')) || '%' and 
                                                  so.name<>sor.name
                                    Order By 
                                        So.name""")

kderp_quotation_revision()


class sale_order(osv.osv):
    _inherit = 'sale.order'
    _name = 'sale.order'
    _description = 'Quotation'
    
    def _get_related_quotations(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for id in ids:
            cr.execute("""Select
                            so.id as order_id
                        from
                            sale_order so
                        inner join
                            sale_order sor on so.name ilike substring(sor.name from 1 for length('2012-SBY-0001')) || '%%' and so.name<>sor.name
                        where
                            sor.id=%d
                        order By
                            so.name""" % (id))
            res[id] = [x[0] for x in cr.fetchall()]
        return res
        
    _columns = {
                "revision_ids":fields.function(_get_related_quotations,type='one2many',relation='sale.order',method=True,string='Related Quotation')
                }
sale_order()
